//
// RegexDirStrainer
//
// Copyright (C) jextra.net.
//
//  This file is part of the Crack build system.
//
//  The Crack build system is free software; you can redistribute it 
//  and/or modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  The Crack build system is distributed in the hope that it will be 
//  useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with the Crack build system; if not, write to the Free
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
//  02111-1307 USA.
//

package net.jextra.crack.type;

import java.io.*;
import java.util.*;
import java.util.regex.*;
import net.jextra.crack.*;
import net.jextra.crack.tool.*;

/**
 * <p>
 * A {@link DirStrainer} that allows you to specify a number of inclusion and exclusion regular expressions that match
 * the entire path of each directory relative to the given root directory.
 * </p>
 * <p>
 * Note, the regular expressions DO NOT include the file name.
 * </p>
 * <p>
 * WARNING: The matching path string is ALWAYS prefixed and suffixed by the "/" character. For example:
 * <code>/net/jextra/crack/</code>. This hopefully makes recursive searching easier.
 * </p>
 * <p>
 * An example use case is to exclude all test directories: <code>".*&#47;test/.*"</code>.
 * </p>
 * <p>
 * Logic:
 * <ol>
 * <li>If no "includes" specified, goto #4.
 * <li>For each include, see if there is a match. If so, goto #4.
 * <li>File should not be included. STOP
 * <li>For each exclude, see if there is a maatch. If so, do not include.
 * <li>File should be included. STOP
 * </ol>
 * </p>
 */
public class RegexDirStrainer implements DirStrainer
{
    // ============================================================
    // Fields
    // ============================================================

    private ArrayList<String> includeRegexs;
    private ArrayList<String> excludeRegexs;
    private File rootDir;

    // ============================================================
    // Constructors
    // ============================================================

    /**
     * Initializes the strainer to return all sub-dirs.
     */
    public RegexDirStrainer()
    {
        init();
    }

    // ============================================================
    // Methods
    // ============================================================

    // ----------
    // public
    // ----------

    public RegexDirStrainer include( String regex )
    {
        includeRegexs.add( regex );
        return this;
    }

    public RegexDirStrainer exclude( String regex )
    {
        excludeRegexs.add( regex );
        return this;
    }

    @Override
    public Collection<File> getDirs( File rootDir )
    {
        assert rootDir != null : "rootDir can not be null";
        assert rootDir.isDirectory() : String.format( "rootDir [%s] must be a directory", rootDir.getAbsolutePath() );

        this.rootDir = rootDir;
        try
        {
            return getDirsRecurse( rootDir );
        }
        catch ( IOException ex )
        {
            throw new CrackException( ex );
        }
    }

    // ----------
    // private
    // ----------

    private void init()
    {
        includeRegexs = new ArrayList<String>();
        excludeRegexs = new ArrayList<String>();
    }

    private Collection<File> getDirsRecurse( File dir )
        throws IOException
    {
        Collection<File> dirs = new LinkedHashSet<File>();

        // Add self if matches path.
        if ( matchDir( dir ) )
        {
            dirs.add( dir );
        }

        for ( File child : dir.listFiles() )
        {
            // Only return directories.
            if ( !child.isDirectory() )
            {
                continue;
            }

            // Add children.
            dirs.addAll( getDirsRecurse( child ) );
        }

        return dirs;
    }

    private boolean matchDir( File dir )
        throws IOException
    {
        //
        // Do includes first.
        //
        boolean matches = includeRegexs.isEmpty();
        for ( String path : includeRegexs )
        {
            if ( matchesPath( dir, path ) )
            {
                matches = true;
                break;
            }
        }

        // Did not match any includes, reject.
        if ( !matches )
        {
            return false;
        }

        //
        // Do excludes last.
        //
        for ( String path : excludeRegexs )
        {
            if ( matchesPath( dir, path ) )
            {
                return false;
            }
        }

        return true;
    }

    private boolean matchesPath( File dir, String regex )
        throws IOException
    {
        Pattern p = Pattern.compile( regex );
        Matcher m = p.matcher( "/" + FileTool.getRelativePath( rootDir, dir ) + "/" );
        boolean matches = m.matches();
        return matches;
    }
}
